import java.text.SimpleDateFormat;


class jqueryDatePickerTagLib {

	def jqDatePicker = {attrs, body ->
		def out = out
		def name = attrs.name
		def id = attrs.id ?: name
		
		SimpleDateFormat sdf = new SimpleDateFormat()
		sdf.applyPattern("dd/MM/yyyy")
		def val = attrs.value ? sdf.format(attrs.value) : ''
		sdf.applyPattern("dd")
		def dia = attrs.value ? sdf.format(attrs.value) : ''
		sdf.applyPattern("MM")
		def mes = attrs.value ? sdf.format(attrs.value) : ''
		sdf.applyPattern("yyyy")
		def ano = attrs.value ? sdf.format(attrs.value) : ''
		
		out.println("<input type='text' name='${name}' id='${id}' value='${val}' />")
		out.println("<input type='hidden' name='${name}_day' id='${id}_day' value='${dia}' />")
		out.println("<input type='hidden' name='${name}_month' id='${id}_month' value='${mes}'  />")
		out.println("<input type='hidden' name='${name}_year' id='${id}_year' value='${ano}' />")
		
		out.println "<script type='text/javascript'> \$(function(){"
		out.println " \$.datepicker.setDefaults( \$.datepicker.regional[ 'pt-BR' ] );"
		out.println "	\$('#${name}').datepicker({"
		out.println "		onClose: function(dateText, inst){"
		out.println "           var split = dateText.split('/'); "
		out.println "			\$(\"#${name}_day\").attr('value',split[0]);"
		out.println "			\$(\"#${name}_month\").attr('value',split[1]);"
		out.println "			\$(\"#${name}_year\").attr('value',split[2]);"
		out.println "		}"
		out.println "	});"
		out.println "});"
		out.println "</script>"
	}
	
}
